<template>
  <el-container>
    <el-header>
      <IndexHeader/>
    </el-header>
    <div style="width: 1200px;height: 1000px;margin: 80px auto" class="articlePost">
        <el-carousel indicator-position="outside" height="313px" width="1000px">
          <el-carousel-item v-for="b in bannerArr">
            <img :src="b.imgUrl" width="100%">
          </el-carousel-item>
        </el-carousel>
        <el-row>
          <el-col span="24">
            <el-card style="border:1px solid blue;border-radius: 10px;">
              <el-form label-width="100px">
                <el-form-item label="标题">
                  <el-input v-model="c.title" style="width: 200px" placeholder="#..."></el-input>
                </el-form-item>
                <el-form-item label="类型" >
                  <el-cascader
                      v-model="categoryId"
                      :placeholder="c.parentName"
                      :options="categoryDataOptions"
                      :props="{checkStrictly: true}"
                      :key="categoryDataOptions.id"
                      clearable="true"
                      @change="handleChange"></el-cascader>
                </el-form-item>
                <el-form-item label="封面">
                  <img v-if="isEdit" :src="oldImgUrl"
                       style="width: 258px;height: 145px;">
                  <el-upload
                      action="http://localhost:8080/v1/uploads/article"
                      name="file"
                      list-type="picture-card"
                      :on-success="handleSuccess"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <img :src="dialogImageUrl" width="200px" height="200px" v-show="dialogImageUrl!=''">
                  <p>请上传格式为jpg/png的图片,且不能超过5MB</p>
                </el-form-item>
                <el-form-item label="内容">
                  <div style="border: 1px solid #ccc;height: 500px" >
                    <quill-editor
                        style="height: 435px;line-height: 20px"
                        v-model="c.content"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @blur="onEditorBlur($event)"
                        @focus=""
                    ></quill-editor>
                  </div>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="post()">发布</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
    </div>
  </el-container>
</template>

<script>
import IndexHeader from "@/components/IndexHeader";
import IndexFooter from "@/components/IndexFooter";
// import MyEditor from "@/components/wangEditor/MyEditor";
import {quillEditor} from "vue-quill-editor";


export default {
  name: "ArticlePostView",
  components: {
    IndexHeader,
    IndexFooter,
    quillEditor,
  },
  data:function (){
    return{
      categoryId:[],
      categoryDataOptions:[],
      TiLength:0,
      editorOption:{},
      c:{
        title:"", imgUrl:"",content:"",videoUrl:"",categoryId:"",brief:"",id:""
      },
      categoryArr:[],
      oldImgUrl:"",
      isEdit:false,
      bannerArr:[],
      dialogVisible:false,
      dialogImageUrl:'',
      file:{},
    }
  },
  methods: {
    handleChange(){},
    /*失去焦点事件*/
    onEditorBlur(quill){
      console.log(("editor blur",quill))
    },
    /*获取焦点事件*/
    onEditorFocus(quill){
      console.log(("editor focus",quill))
    },
    /*准备富文本编辑器*/
    onEditorReady(quill){
      console.log(("editor ready",quill))
    },
    /*内容改变时间*/
    onEditorChange({quill,html,text}){
      console.log("editor change!",quill,html,text);
      this.c.content=html;
    },
    onInput(value) {
      console.log(value)
      this.c.content = value // 将编辑器内容存储到 content 变量
    },
    post(){
      const parser = new DOMParser();
      const parsedContents = parser.parseFromString(this.c.content, 'text/html');
      const plainText = parsedContents.body.textContent.trim();
      this.c.brief= plainText.slice(0,120) +"...";
      //发出请求
      this.c.imgUrl=this.url;
      this.c.categoryId = this.categoryId[this.categoryId.length-1]
      console.log(this.c)
      if (this.c.title==""||this.c.title==null){
        this.$message.error("请输入文章标题!");
        return;
      }
      if (this.c.imgUrl==""){
        this.$message.error("请选择一张封面图!");
        return;
      }
      if (this.c.categoryId==null||this.c.categoryId==""){
        this.$message.error("请选择分类!");
        return;
      }
      if (this.c.content==null||this.c.content==""){
        this.$message.error("请输入文章内容!");
        return;
      }
      let formdata = this.qs.stringify(this.c)
      this.axios
          .create({
            'headers':{
              'Authorization': localStorage.getItem('localJwt')
            }
          })
          .post("http://localhost:8080/v1/contents/post",formdata).then((response) => {
        if (response.data.code==1){
          console.log('保存文章到数据库: ', { content: this.c.content, brief: this.c.brief })
          console.log("正在处理发送请求!")
          if(location.href.includes("id")){
            this.$message.success("修改完成");
            history.back();
            return;
          }
          this.$message.success("发布完成!");
          history.back();
        }else{
          this.$message.error(response.data.msg);
        }
      })
    },
    handleInput(){
      this.c.content = this.quill.root.innerHTML;
    },
    handleSuccess(response,file,fileList,url){//当上传成功时此方法会执行
      // response==file.response 代表服务器响应的ResultVo
        this.url = response.data.url;
        this.file = response.data;
        console.log(this.file)
      this.dialogImageUrl=''

    },
    handleRemove(file, fileList) {
      this.url="";
      //发出删除文件的请求   file.response上传成功时服务器响应的内容ResultVO
      let formdata = this.qs.stringify(this.file)
      this.axios
          .create({
            'headers':{
              'Authorization': localStorage.getItem('localJwt')
            }
          })
          .post("http://localhost:8080/v1/uploads/remove",formdata).then(function () {
        console.log("服务器文件删除完成!");
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    loadArticle(){
      if(location.href.includes("id")) {
        let id = this.$router.currentRoute.query.id;
        console.log(id)
        let url = 'http://localhost:8080/v1/contents/detail?id=' + id;
        console.log(url)
        this.axios
            .create({
              'headers': {
                'Authorization': localStorage.getItem('localJwt')
              }
            })
            .get(url).then((response) => {
          this.c = response.data.data;
          this.dialogImageUrl=this.c.imgUrl;
          console.log(this.c)
          this.categoryId.push(3)
        })
      }
    },
    isLogin(){
      if(localStorage.getItem("id")){
        if(this.$router.path.includes("/articlePost")){
          return
        }else{
          location.href='/articlePost';
        }
      }else{
        this.$message.error("未登录,请先登录!");
        location.href='/login';
      }
    }
  },
  mounted(){

    this.loadArticle();
    //请求所有轮播图数据
    this.axios
        .create({
          'headers':{
            'Authorization': localStorage.getItem('localJwt')
          }
        })
        .get("http://localhost:8080/v1/banners/1").then((response)=> {
      if (response.data.code==1){
        this.bannerArr = response.data.data;
      }
    })

    this.axios
        .create({
          'headers':{
            'Authorization': localStorage.getItem('localJwt')
          }
        })
        .get("http://localhost:8080/v1/category/tree?id=1").then((response)=> {
      if (response.data.code==1){
        this.categoryDataOptions = response.data.data;
      }
    }),
        this.isLogin();
  }
}
</script>

<style>
a{text-decoration: none;font-size: 14px;text-align: center}
a:link{color:#cccccc }
a:hover{color: white}
.center{width: 1200px;margin: 0 auto}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.el-menu-item{
  margin: 0 35px;
}
.el-avatar--circle{
  vertical-align: bottom;
}
.con{
  margin: 0;
  padding: 0;
  eight: 25px;
  line-height: 25px;
}
li.el-menu-item.con{
  height:30px;
}

</style>
